#!/usr/bin/perl -w

# After cloning the modules of a Stripes development environment --
# consisting of one or more of the stripes-* and ui-* git modules from
# https://github.com/folio-org/ -- run this script in the directory
# that contains them to set up yarn linking. The first time you run
# it, use the "-i" option to initialise the low-level repositories as
# yarn-link destinations. Thereafter it can be omitted.

use strict;
use warnings;

if (@ARGV && $ARGV[0] eq '--really') {
    shift @ARGV;
} else {
    print STDERR "$0: using `yarn link` is deprecated in Stripes\
See https://tinyurl.com/new-stripes
If you want to use this script, supply '--really' as the FIRST argument\n";
    exit 1;
}

my $initialise = 0;
if (@ARGV && $ARGV[0] eq '-i') {
    $initialise = 1;
    shift @ARGV;
    print "Initialising\n";
}

if (@ARGV == 1) {
    chdir $ARGV[0];
    print "Running in directory $ARGV[0]\n";
} elsif (@ARGV != 0) {
    print STDERR "Usage: $0 [-i] [<directory>]\n";
    exit 1;
}

if ($initialise) {
    foreach my $dir (<stripes-* ui-* ui-plugin-example/plugin-*>) {
	if ($dir =~ /-platform$/) {
	    print "* Skipping linkability for platform '$dir'\n";
	} elsif ($dir eq 'ui-plugin-example') {
	    print "* Skipping linkability for platform '$dir'\n";
	} else {
	    print "* Initialising linkability for '$dir'\n";
	    # Stupidly, there is no way to ask yarn whether there is
	    # already a link in place, so the best we can do is try to
	    # unlink and discard whatever error it emits.
	    system "cd $dir && yarn unlink > /dev/null 2>&1 || true";
	    system "cd $dir && yarn link"
	}
    }
    exit;
}

foreach my $dir (<stripes-* ui-*>) {
    if (! -f "$dir/package.json") {
	print "* Skipping '$dir' -- no package.json\n";
	next;
    }
    print "* Linking for '$dir'\n";
    my $deps = `grep '^ *"\@folio/' $dir/package.json`;
    foreach my $line (split /\n/, $deps) {
	my($name) = ($line =~ /.*"(\@folio\/.*?)"/);
	system "cd $dir && yarn link \"$name\"";
    }

    if ($dir ne 'stripes-core' &&
	-d "$dir/node_modules" &&
	(`grep '"react"' $dir/package.json` || -d "$dir/node_modules/react")) {
	system("rm -rf $dir/node_modules/react");
	symlink("../../stripes-core/node_modules/react", "$dir/node_modules/react") ||
	    print STDERR "$0: can't symlink $dir/node_modules/react: $!\n";
	system("ls -ld $dir/node_modules/react");
    }
}
